<template>
  <div class="test-container" ref="testContainerRef">
    <back-header
      :customBack="myNavigator"
      :title="testSubject"
      :titleSize="16"
      :titleBold="false"
    >
      <template #icon>
        <van-icon name="records" size="24" />
      </template>
    </back-header>

    <!-- 添加一个空的占位div，高度与header相同 -->
    <div style="height: 56px"></div>

    <div class="content">
      <!-- 题目信息 -->
      <div class="progress-info">
        <van-progress :percentage="percent" :show-pivot="false" />
        <div class="time-info">
          剩余时间:
          {{ formatTime(Math.floor(testTime - (testTime * percent) / 100)) }}
        </div>
        <div class="question-count">{{ index + 1 }}/{{ total }}</div>
      </div>

      <!-- 内容区域 -->
      <div class="context_item">
        <div :key="item.id" class="head_item">
          {{ index + 1 }}.{{ item.question }}
        </div>
        <!-- 单选框 -->
        <van-radio-group
          class="option-group"
          v-model="selectedRatio"
          v-show="item.answer.length == 1"
          @change="radioHandler"
        >
          <div class="option-item">
            <van-radio name="A" clickable>
              {{ item.item1 }}
            </van-radio>
          </div>
          <div class="option-item">
            <van-radio name="B" clickable>
              {{ item.item2 }}
            </van-radio>
          </div>
          <div class="option-item">
            <van-radio name="C" clickable>
              {{ item.item3 }}
            </van-radio>
          </div>
          <div class="option-item" v-if="item.item4">
            <van-radio name="D" clickable>
              {{ item.item4 }}
            </van-radio>
          </div>
        </van-radio-group>

        <!-- 多选框 -->
        <van-checkbox-group
          class="option-group"
          v-model="selectedChecked"
          v-show="item.answer.length > 1"
          @change="checkHandler"
        >
          <div class="option-item">
            <van-checkbox shape="square" name="A">
              {{ item.item1 }}
            </van-checkbox>
          </div>
          <div class="option-item">
            <van-checkbox shape="square" name="B">
              {{ item.item2 }}
            </van-checkbox>
          </div>
          <div class="option-item">
            <van-checkbox shape="square" name="C">
              {{ item.item3 }}
            </van-checkbox>
          </div>
          <div class="option-item" v-if="item.item4">
            <van-checkbox shape="square" name="D">
              {{ item.item4 }}
            </van-checkbox>
          </div>
        </van-checkbox-group>
      </div>

      <!-- 题目导航 - 优化版 -->
      <!-- <div class="func_item">
        <van-button type="primary" size="mini" icon="arrow-left" @click="prev">
          上一题
        </van-button>

        <div class="picker_box">
          <van-field
            v-model="navIndex"
            style="width: 40px"
            type="digit"
            :min="1"
            :max="total"
          />
          <van-button
            type="primary"
            size="mini"
            style="margin-left: 5px"
            @click="goToQuestion"
          >
            跳转
          </van-button>
        </div>

        <van-button type="primary" size="mini" icon="arrow" @click="next">
          下一题
        </van-button>

        <van-button
          :type="getIcon != 'star' ? 'primary' : 'warning'"
          size="mini"
          :icon="getIcon"
          @click="tap(index)"
        >
          标记
        </van-button>

        <van-button
          type="danger"
          size="mini"
          icon="completed"
          @click="submitExam(true)"
        >
          交卷
        </van-button>
      </div> -->
    </div>

    <!-- 题目选择区弹窗 -->
    <van-popup
      v-model:show="questionSelectorVisible"
      position="bottom"
      :style="{ height: '60%' }"
      round
      closeable
    >
      <div class="question-selector-popup">
        <div class="popup-title">题目选择</div>
        <div class="legend">
          <div class="legend-item">
            <div class="legend-box normal"></div>
            <span>未答题</span>
          </div>
          <div class="legend-item">
            <div class="legend-box answered"></div>
            <span>已答题</span>
          </div>
          <div class="legend-item">
            <div class="legend-box marked"></div>
            <span>已标记</span>
          </div>
          <div class="legend-item">
            <div class="legend-box current"></div>
            <span>当前题</span>
          </div>
        </div>
        <div class="question-grid">
          <div
            v-for="(_, i) in items"
            :key="i"
            class="question-box"
            :class="{
              'answered': isQuestionAnswered(i),
              'marked': tapIndex.includes(i),
              'current': i === index
            }"
            @click="selectQuestion(i)"
          >
            {{ i + 1 }}
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 放在外部使其正确显示 -->
    <van-action-bar safe-area-inset-bottom style="height: 8vh">
      <van-action-bar-icon
        color="#FF7744"
        @click="tap(index)"
        :icon="getIcon"
        text="标记"
      />
      <van-action-bar-icon
        @click="toggleQuestionSelector"
        color="#3388ff"
        icon="apps-o"
        text="题目"
      />
      <van-action-bar-icon
        @click="submitExam(true)"
        color="#ff0000"
        icon="completed"
        text="交卷"
      />
      <van-field
        v-model="navIndex"
        style="width: 30px; background-color: #f0f8ff"
        type="digit"
        :min="1"
        :max="total"
      />
      <span style="font-size: 13px; margin-left: 5px">/{{ total }}</span>
      <van-action-bar-icon
        icon="share-o"
        color="#00dd00"
        @click="goToQuestion"
        text="跳转"
      />
      <van-action-bar-button class="prev-button" @click="prev" text="上一题" />
      <van-action-bar-button class="next-button" @click="next" text="下一题" />
    </van-action-bar>
  </div>
</template>

<script setup>
import BackHeader from "@/components/common/BackHeader.vue";
import { ref, watch, onMounted, onBeforeUnmount, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { showToast, showDialog, showNotify } from "vant";
import { useStore } from "vuex";
import selfTestApi from "@/api/selfTest/index";
import zhiZhaoApi from "@/api/questionItem/questionItem";
import subjectTest from "@/api/subject/test";
import { onBeforeRouteLeave } from "vue-router";

// 题目选择弹窗状态
const questionSelectorVisible = ref(false);

// 切换题目选择器显示状态
const toggleQuestionSelector = () => {
  questionSelectorVisible.value = !questionSelectorVisible.value;
};

// 选择题目
const selectQuestion = (questionIndex) => {
  saveCurrentAnswer(); // 保存当前答案
  index.value = questionIndex;
  questionSelectorVisible.value = false; // 选择后关闭弹窗
};

// 判断题目是否已答
const isQuestionAnswered = (questionIndex) => {
  if (!allAnswers.value || !allAnswers.value[questionIndex]) return false;
  return allAnswers.value[questionIndex].some(answer => answer !== "");
};

const getIcon = computed(() => {
  // console.log(tapIndex.value, index.value);

  return tapIndex.value.includes(index.value) ? "star" : "star-o";
});

const myNavigator = () => {
  if (route.path == "/trainingexam") {
    router.push("/training/courses");
  } else if (route.path == "/learning/selfTest") {
    router.push("/learning");
  } else if (route.path == "/test/startTest") {
    router.push("/test/info");
  }
};

const testSubject = computed(() => {
  if (route.query.type == "subjectTest") {
    return "考试科目：" + route.query.name;
  } else if (route.path == "/test/startTest") {
    return route.query.title;
  } else if (store.getters.selectValue) {
    const index = store.getters.selectValue.indexOf("/");
    if (index != -1) {
      const arr = store.getters.selectValue.split("/");
      return "考试科目：" + arr[1];
    } else {
      return "考试科目：" + store.getters.selectValue;
    }
  } else {
    return "考试科目";
  }
});
const router = useRouter();
const route = useRoute();
const store = useStore();

// 响应式状态

let questionItemId = 0;
const index = ref(0);
const total = ref(0);
const items = ref([]);
const item = ref({
  subject: "",
  question: "",
  item1: "",
  item2: "",
  item3: "",
  item4: "",
  answer: "",
});
const selectedRatio = ref("");
const selectedChecked = ref([]);
const allAnswers = ref([]);
const tapIndex = ref([]);
const percent = ref(0);
const testTime = ref(5);
const setInter = ref(null);
const warningTimer = ref(null);
const isWarningShown = ref(false);
const canRoute = ref(false); //控制是否可以直接跳转出路由
const navIndex = ref(1);

// 当页面隐藏时，自动交卷
// const handleVisiable = (e) => {
//   switch (e.target.visibilityState) {
//     case "hidden":
//       ElMessage.warning("警告！你已经离开当前答题页面，5秒后自动交卷！");
//       setTimeout(() => {
//         submitExam();
//       }, 5000);
//       break;
//   }
// };

const toggleCheckbox = (value) => {
  const index = selectedChecked.value.indexOf(value);
  if (index === -1) {
    selectedChecked.value.push(value);
  } else {
    selectedChecked.value.splice(index, 1);
  }
  checkHandler();
};

const radioHandler = () => {
  // 只清除当前题目的答案
  for (let i = 0; i < 4; i++) {
    allAnswers.value[index.value][i] = "";
  }
  // 直接保存当前单选答案
  switch (selectedRatio.value) {
    case "A":
      allAnswers.value[index.value][0] = selectedRatio.value;
      break;
    case "B":
      allAnswers.value[index.value][1] = selectedRatio.value;
      break;
    case "C":
      allAnswers.value[index.value][2] = selectedRatio.value;
      break;
    case "D":
      allAnswers.value[index.value][3] = selectedRatio.value;
      break;
  }
};

const checkHandler = () => {
  // 只清除当前题目的答案
  for (let i = 0; i < 4; i++) {
    allAnswers.value[index.value][i] = "";
  }
  // 直接保存当前多选答案
  selectedChecked.value.forEach((element) => {
    switch (element) {
      case "A":
        allAnswers.value[index.value][0] = element;
        break;
      case "B":
        allAnswers.value[index.value][1] = element;
        break;
      case "C":
        allAnswers.value[index.value][2] = element;
        break;
      case "D":
        allAnswers.value[index.value][3] = element;
        break;
    }
  });
};

/**
 * 交卷
 * @param flag 是否自动交卷
 */
const submitExam = (flag) => {
  if (!flag) {
    submitTitle();
  } else {
    if (tapIndex.value.length > 0) {
      showDialog({
        title: "确认框",
        message: "还有标记的题目哦，不去看看吗",
        confirmButtonText: "检查一下",
        cancelButtonText: "直接交卷",
        showCancelButton: true,
      })
        .then(() => {
          item.value = items.value[tapIndex.value[0]];
          index.value = tapIndex.value[0];
        })
        .catch(() => {
          submitTitle();
        });
    } else {
      showDialog({
        title: "确认框",
        message: "是否确认交卷？",
        confirmButtonText: "直接交卷",
        cancelButtonText: "检查一下",
        showCancelButton: true,
      }).then(() => {
        submitTitle();
      });
    }
  }
};

const tap = (i) => {
  if (tapIndex.value.includes(i)) {
    tapIndex.value = tapIndex.value.filter((e) => e !== i);
  } else {
    tapIndex.value.push(i);
  }
};

// 添加一个函数专门用于保存当前答案
const saveCurrentAnswer = (questionIndex = index.value) => {
  // 获取当前要保存的题目信息
  const currentQuestion = items.value[questionIndex];
  
  // 判断是单选还是多选，基于题目的answer属性长度
  const isSingleChoice = currentQuestion.answer.length === 1;
  
  if (isSingleChoice && selectedRatio.value) {
    // 保存单选题答案
    for (let i = 0; i < 4; i++) {
      allAnswers.value[questionIndex][i] = "";
    }
    // 使用正确的索引保存答案
    switch (selectedRatio.value) {
      case "A":
        allAnswers.value[questionIndex][0] = selectedRatio.value;
        break;
      case "B":
        allAnswers.value[questionIndex][1] = selectedRatio.value;
        break;
      case "C":
        allAnswers.value[questionIndex][2] = selectedRatio.value;
        break;
      case "D":
        allAnswers.value[questionIndex][3] = selectedRatio.value;
        break;
    }
  } else if (!isSingleChoice && selectedChecked.value.length > 0) {
    // 保存多选题答案
    for (let i = 0; i < 4; i++) {
      allAnswers.value[questionIndex][i] = "";
    }
    // 使用正确的索引保存答案
    selectedChecked.value.forEach((element) => {
      switch (element) {
        case "A":
          allAnswers.value[questionIndex][0] = element;
          break;
        case "B":
          allAnswers.value[questionIndex][1] = element;
          break;
        case "C":
          allAnswers.value[questionIndex][2] = element;
          break;
        case "D":
          allAnswers.value[questionIndex][3] = element;
          break;
      }
    });
  }
};

// 监听器
watch(index, (newVal, oldVal) => {
  // 先保存当前题目的答案（如果是从其他题切换过来的）
  if (oldVal !== newVal) {
    saveCurrentAnswer(oldVal);
  }
  
  // 重置当前选项状态
  selectedRatio.value = "";
  selectedChecked.value = [];
  
  // 设置当前题目
  item.value = items.value[newVal];
  navIndex.value = newVal + 1;
  
  // 恢复已保存的答案
  const res = allAnswers.value[newVal].filter((a) => a != "");
  if (items.value[newVal].answer.length > 1) {
    selectedChecked.value = res;
  } else {
    selectedRatio.value = res[0];
  }
});

// 修改 next 和 prev 函数，确保在切换之前保存当前答案
const next = () => {
  if (index.value == total.value - 1) {
    showToast({
      type: "fail",
      message: "已经是最后一题了！",
    });
    return;
  }
  saveCurrentAnswer(); // 保存当前答案
  index.value = index.value + 1;
};

const prev = () => {
  if (index.value == 0) {
    showToast({
      type: "fail",
      message: "已经是第一题了！",
    });
    return;
  }
  saveCurrentAnswer(); // 保存当前答案
  index.value = index.value - 1;
};

const submitTitle = () => {
  // 设置标志，表明正在提交
  canRoute.value = true;

  let rightNum = 0;
  for (let i = 0; i < allAnswers.value.length; i++) {
    let element = allAnswers.value[i].filter((a) => a != "");
    element.sort();
    const selected = element.join("+");
    if (selected == items.value[i].answer) {
      rightNum++;
    }
  }
  const score = Math.round((rightNum / total.value) * 100);
  clearInterval(setInter.value);
  let ids = items.value.map((item) => item.id);
  // 如果路由参数里没有type，则认为是考试，如果有type，则认为是自测
  if (!route.query.type) {
    zhiZhaoApi
      .submit(
        score,
        Math.round((percent.value * testTime.value) / 100),
        questionItemId,
        store.getters.name,
        allAnswers.value,
        ids,
        route.query.title
      )
      .then((res) => {
        showNotify({ type: "success", message: res.message });
        store.dispatch("learn/setPaperCount", store.getters.paperCount - 1);
        router.push("/test/myexams");
      });
  } else {
    if (route.query.type === "selfTest") {
      selfTestApi
        .submit(
          score,
          Math.round((percent.value * testTime.value) / 100),
          questionItemId,
          store.getters.name,
          allAnswers.value,
          ids
        )
        .then((res) => {
          showNotify({ type: "success", message: res.message });
          router.push({
            path: "/learning/review",
            query: { selectedId: store.getters.selectedId },
          });
        });
    } else if (route.query.type === "subjectTest") {
      subjectTest
        .submit(
          score,
          questionItemId,
          Math.round((percent.value * testTime.value) / 100)
        )
        .then((res) => {
          showNotify({ type: "success", message: res.message });
          router.push({
            path: "/training/courses",
          });
        })
        .catch((err) => {
          router.push({
            path: "/training/courses",
          });
        });
    }
  }
};

// 生命周期钩子
onMounted(async () => {
  if (Object.keys(route.query).length == 0) {
    canRoute.value = true;
    router.push("/home");
    return;
  }

  questionItemId = route.query.questionItemId;
  const type = route.query.type;

  try {
    // const res = await (type
    //   ? selfTestApi.batchGet(questionItemId)
    //   : zhiZhaoApi.batchGet(questionItemId));

    let res = null;
    if (type) {
      if (type == "selfTest") {
        try {
          res = await selfTestApi.batchGet(questionItemId);
        } catch (error) {
          canRoute.value = true;
          router.push("/learning");
          return;
        }
      } else if (type == "subjectTest") {
        try {
          res = await subjectTest.batchGet(questionItemId);
        } catch (error) {
          canRoute.value = true;
          router.push("/training");
          return;
        }
      }
    } else {
      try {
        res = await zhiZhaoApi.batchGet(questionItemId);
      } catch (error) {
        canRoute.value = true;
        router.push("/test");
        return;
      }
    }

    items.value = res.data.result;
    testTime.value = res.data.time;
    item.value = items.value[0];
    total.value = items.value.length;

    // 初始化答案数组
    allAnswers.value = Array(total.value)
      .fill()
      .map(() => Array(4).fill(""));

    // 启动计时器
    let t1 = 1;
    setInter.value = setInterval(() => {
      t1++;
      percent.value = (t1 / testTime.value) * 100;
      if (Math.round(percent.value) == 100) {
        submitExam(false);
      }
    }, 1000);

    // 添加页面刷新事件监听
    // window.addEventListener("beforeunload", handleBeforeUnload);

    // 初始计算文本高度
  } catch (error) {
    console.error("Error fetching questions:", error);
    showToast({
      type: "fail",
      message: "获取题目失败",
    });
    if (!type) {
      canRoute.value = true;
      router.push("/index");
    }
  }
  // if (route.path == "/test/startTest") {
  // } else {
  // }
  // 除了自我测试，都会监控页面，如果离开页面，3秒后自动交卷
  // if (route.query.type != "selfTest") {
  //   document.addEventListener("visibilitychange", handleVisibilityChange);
  // }
});

onBeforeUnmount(() => {
  if (route.query.type != "selfTest") {
    clearInterval(setInter.value);
    if (warningTimer.value) {
      clearInterval(warningTimer.value);
    }
    // document.removeEventListener("visibilitychange", handleVisibilityChange);
  }
  // window.removeEventListener("beforeunload", handleBeforeUnload);
});

// 添加时间格式化函数
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;

  const parts = [];
  if (hours > 0) parts.push(`${hours}小时`);
  if (minutes > 0) parts.push(`${minutes}分`);
  parts.push(`${remainingSeconds}秒`);

  return parts.join("");
};

// // Add navigation guard
// onBeforeRouteLeave(async (to, from, next) => {
//   // 如果是通过提交触发的路由跳转，直接允许
//   if (canRoute.value) {
//     next();
//     return;
//   }

//   // For self tests
//   if (route.query.type === "selfTest") {
//     try {
//       const result = await showDialog({
//         title: "提示",
//         message: "离开页面将删除此次测试，是否确认离开？",
//         confirmButtonText: "确认",
//         cancelButtonText: "取消",
//         showCancelButton: true,
//       });

//       if (result === "confirm") {
//         // Delete the self test
//         await selfTestApi.deleteById(questionItemId);
//         next();
//       } else {
//         next(false);
//       }
//     } catch {
//       // User clicked cancel
//       next(false);
//     }
//   }
//   // For non-self tests
//   else {
//     try {
//       const result = await showDialog({
//         title: "提示",
//         message: "离开页面将自动交卷，是否确认离开？",
//         confirmButtonText: "确认",
//         cancelButtonText: "取消",
//         showCancelButton: true,
//       });

//       if (result === "confirm") {
//         submitTitle();
//         next();
//       } else {
//         next(false);
//       }
//     } catch {
//       // User clicked cancel
//       next(false);
//     }
//   }
// });

const goToQuestion = () => {
  if (navIndex.value < 1 || navIndex.value > total.value) {
    showToast({
      type: "fail",
      message: "请输入有效的题号",
    });
    return;
  }
  saveCurrentAnswer(); // 保存当前答案
  index.value = parseInt(navIndex.value) - 1;
};

// 添加处理页面刷新的函数
const handleBeforeUnload = (event) => {
  console.log("123");

  // 对于自测试不自动交卷，仅对其他类型的考试执行
  if (route.query.type !== "selfTest" && !canRoute.value) {
    // 显示提示信息（大多数现代浏览器会忽略自定义消息）
    const message = "刷新页面将自动交卷！";
    event.preventDefault();
    event.returnValue = message;

    // 尝试提交考试（注意：此时页面即将刷新，可能无法完成异步操作）
    submitExam(false);

    // 返回自定义消息（虽然大多数浏览器会显示标准消息）
    return message;
  }
};

// 处理页面可见性变化
const handleVisibilityChange = () => {
  if (document.hidden) {
    // 记录离开时的时间戳
    const leaveTime = Date.now();

    // 显示警告
    isWarningShown.value = true;
    showToast({
      type: "fail",
      message: "警告！检测到您已离开考试页面，3秒后将自动交卷！",
    });

    // 使用时间戳检查而不是setTimeout
    warningTimer.value = setInterval(() => {
      const currentTime = Date.now();
      const timeAway = currentTime - leaveTime;

      if (timeAway >= 3000 && isWarningShown.value) {
        clearInterval(warningTimer.value);
        showToast({
          type: "fail",
          message: "您已离开考试页面超过3秒，系统将自动交卷！",
        });
        submitExam(false);
      }
    }, 100); // 每100ms检查一次
  } else {
    // 用户返回页面
    if (isWarningShown.value) {
      isWarningShown.value = false;
      if (warningTimer.value) {
        clearInterval(warningTimer.value);
      }
      showToast({
        type: "success",
        message: "您已返回考试页面，可以继续答题",
      });
    }
  }
};
</script>

<style scoped>
/* 确保容器从顶部开始 */
.test-container {
  padding-top: 0;
  background-color: #f7f8fa;
  display: flex;
  flex-direction: column;
  /* 为测试容器添加底部间距，防止内容被ActionBar遮挡 */
  padding-bottom: 8vh; /* 或与ActionBar高度相等的值 */
}

.content {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.progress-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.time-info,
.question-count {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #646566;
}

.head_item {
  font-size: 16px;
  font-weight: bold;
  line-height: 1.5;
}

.option-group {
  width: 96%;
  padding: 0;
}

.option-item {
  width: 96%;
  margin-top: 10px;
}

.option-item :deep(.van-radio),
.option-item :deep(.van-checkbox) {
  width: 100%;
  padding: 12px;
  background-color: #f8f8f8;
  border-radius: 6px;
}

.option-item :deep(.van-radio__label),
.option-item :deep(.van-checkbox__label) {
  white-space: normal;
  word-break: break-word;
}

.func_item {
  display: flex;
  margin-top: 10px;
  justify-content: space-between;
}

.picker_box {
  display: flex;
  align-items: center;
  margin: 0 4px;
}

:deep(.van-button--mini) {
  min-width: 0;
  padding: 0 5px;
  height: 22px;
  font-size: 10px;
  flex-shrink: 0;
}

:deep(.van-field) {
  padding: 0;
  width: 30px;
}

:deep(.van-field__control) {
  text-align: center;
  height: 22px;
  padding: 0;
  font-size: 12px;
}

@media (prefers-color-scheme: dark) {
  .test-container {
    background-color: #1a1a1a;
  }
  .option-item :deep(.van-radio),
  .option-item :deep(.van-checkbox) {
    background-color: #2c2c2c;
  }
}

/* 添加这些样式来确保ActionBar正确显示 */
:deep(.van-action-bar) {
  z-index: 999;
}

/* 蓝色渐变按钮样式 */
:deep(.prev-button) {
  background-image: linear-gradient(to right, #4facfe, #00f2fe) !important;
  border: none !important;
}

:deep(.next-button) {
  background-image: linear-gradient(to right, #0072ff, #00c6ff) !important;
  border: none !important;
}

/* 修改 ActionBar 整体样式 */
:deep(.van-action-bar) {
  box-shadow: 0 -2px 10px rgba(0, 114, 255, 0.1);
  background-color: #ffffff;
  z-index: 999;
}

/* 修改 ActionBar 图标颜色 */
:deep(.van-action-bar-icon__icon) {
  transition: all 0.3s ease;
}

:deep(.van-action-bar-icon:active .van-action-bar-icon__icon) {
  transform: scale(1.1);
}

/* 输入框美化 */
:deep(.van-field__control) {
  border: 1px solid #e0e0ff;
  border-radius: 4px;
  background-color: #f0f8ff;
}

/* 题目选择器弹窗样式 */
.question-selector-popup {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.popup-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.legend {
  display: flex;
  justify-content: space-around;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  margin: 5px;
}

.legend-box {
  width: 20px;
  height: 20px;
  margin-right: 5px;
  border-radius: 4px;
}

.legend-box.normal {
  background-color: #f1f1f1;
  border: 1px solid #ddd;
}

.legend-box.answered {
  background-color: #d4edda;
  border: 1px solid #c3e6cb;
}

.legend-box.marked {
  background-color: #fff3cd;
  border: 1px solid #ffeeba;
}

.legend-box.current {
  background-color: #cce5ff;
  border: 1px solid #b8daff;
}

.question-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  overflow-y: auto;
  flex: 1;
  padding: 10px 0;
}

.question-box {
  background-color: #f1f1f1;
  border: 1px solid #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  height: 40px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.2s ease;
}

.question-box:active {
  transform: scale(0.95);
}

.question-box.answered {
  background-color: #d4edda;
  border-color: #c3e6cb;
  color: #155724;
}

.question-box.marked {
  background-color: #fff3cd;
  border-color: #ffeeba;
  color: #856404;
}

.question-box.current {
  background-color: #cce5ff;
  border-color: #b8daff;
  color: #004085;
}

.question-box.marked.answered {
  background: linear-gradient(135deg, #d4edda 50%, #fff3cd 50%);
  color: #155724;
}

.question-box.marked.current {
  background: linear-gradient(135deg, #cce5ff 50%, #fff3cd 50%);
  color: #004085;
  border: 2px solid #0066cc;
}

.question-box.answered.current {
  background: linear-gradient(135deg, #cce5ff 50%, #d4edda 50%);
  color: #004085;
  border: 2px solid #0066cc;
}

.question-box.marked.answered.current {
  background: linear-gradient(135deg, #cce5ff 33%, #d4edda 33%, #d4edda 66%, #fff3cd 66%);
  color: #004085;
  border: 2px solid #0066cc;
}

@media (prefers-color-scheme: dark) {
  .test-container {
    background-color: #1a1a1a;
  }
  .option-item :deep(.van-radio),
  .option-item :deep(.van-checkbox) {
    background-color: #2c2c2c;
  }
  
  .question-box {
    background-color: #333;
    border-color: #444;
    color: #ddd;
  }
  
  .question-box.answered {
    background-color: #264d33;
    border-color: #2e5a3e;
    color: #a3d9a5;
  }
  
  .question-box.marked {
    background-color: #4d4d25;
    border-color: #5a5a2e;
    color: #e6e6a3;
  }
  
  .question-box.current {
    background-color: #25344d;
    border-color: #2e3e5a;
    color: #a3c1e6;
  }
  
  .popup-title {
    color: #ddd;
  }
  
  .legend-box.normal {
    background-color: #333;
    border-color: #444;
  }
  
  .legend-box.answered {
    background-color: #264d33;
    border-color: #2e5a3e;
  }
  
  .legend-box.marked {
    background-color: #4d4d25;
    border-color: #5a5a2e;
  }
  
  .legend-box.current {
    background-color: #25344d;
    border-color: #2e3e5a;
  }
}
</style>
